package com.easyexcel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

public class TestEasyExcel {
	
	public static MyData myData = new MyData();
	
	public static void main(String[] args) {
		generateMyData();
		 // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        String templateFileName = "D:\\AijunTao\\Desktop\\easyexcel\\template.xlsx";

        String fileName =  "D:\\AijunTao\\Desktop\\easyexcel\\data.xlsx";

        try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
            fillConfig.setHasInit(false);
            // 如果有多个list 模板上必须有{前缀.} 这里的前缀就是 data1，然后多个list必须用 FillWrapper包裹
            excelWriter.fill(new FillWrapper("head", myData.getHeads()), fillConfig, writeSheet);
            excelWriter.fill(new FillWrapper("body", myData.getBodys()), writeSheet);

            Map<String, Object> map = new HashMap<String, Object>();
            //map.put("date", "2019年10月9日13:28:28");
            map.put("date", new Date());

            excelWriter.fill(map, writeSheet);
        }
	}

	
	private static void generateMyData() {
		List<Head> heads = new ArrayList();
		Head h1 = Head.builder().acount("h1").build();
		Head h2 = Head.builder().acount("h2").build();
		Head h3 = Head.builder().acount("h3").build();
		heads.add(h1);heads.add(h2);heads.add(h3);
		myData.setHeads(heads);
		
		List<Body> bodys = new ArrayList();
		for (int i=0; i<10; i++ ) {
			Body body = Body.builder()
					.busType("1")
//					.acounts(new ArrayList() {{
//						add("a1");add("a2");add("a3");
//					}})
					.avaAmount(new BigDecimal(i))
					.useAmount(new BigDecimal(i))
					.build();
			bodys.add(body);
		}
		myData.setBodys(bodys);
	}


	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	static class Head {
		private String acount;
	}
	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	static class Body {
		private String busType;
//		private List<String> acounts;
		private BigDecimal avaAmount;
		private BigDecimal useAmount;
	}
	
	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	static class MyData {
		private List<Head> heads;
		private List<Body> bodys;
	}
}
